#!/usr/bin/env python

import web
import time
from base import adminAction
import config
import log
import cgi
import utils
import os

class uploadAction(adminAction):
    def __init__(self):
        adminAction.__init__(self)

    def GET(self, name):
        if not name:
            return self.index()
        else:
            return self.notFound()    

    def index(self):
        return self.display('uploadFile')

    def POST(self, name):
        cgi.maxlen = int(config.MAX_UPLOAD_FILE_SIZE) * 1024 * 1024 # 2MB
        if name == 'upload':
            try:
                i = web.input(file={})
            except ValueError:
                return self.error(msg='File size exceeds 2Mb!')
            return self.upload()
        else:
            return self.notFound()

    def upload(self):
        inputParams = web.input(uploadFile={})
        uploadDir = config.UPLOAD_DIR 
        if not os.path.exists(uploadDir):
            os.makedirs(uploadDir)

        if 'uploadFile' in inputParams: 
            filename=utils.uuidgen()+".jpg"
            fout = open(uploadDir +'/'+ filename, 'w') 
            fout.write(inputParams.uploadFile.file.read()) 
            fout.close() 

        self.privData['text'] = config.URL+'/'+ config.UPLOAD_DIR+filename
        return self.display('copyText')
